using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : Singleton<ObjectPool>
{
    private Dictionary<string, List<GameObject>> _pool;

    private ObjectPool()
    {
        _pool = new Dictionary<string, List<GameObject>>();
    }

    public GameObject SpawnObject(string path)
    {
        GameObject needGo;
        if (_pool.ContainsKey(path) && _pool[path].Count > 0 && _pool[path][0] != null)
        {
            needGo = _pool[path][0];
            _pool[path].RemoveAt(0);
        }
        else
        {
            needGo = AssetsManager.PrefabManager.GetInstance().CreateGameObjectByPrefab(path);
            //去掉(clone)
            needGo.name = path;
        }

        needGo.SetActive(true);
        return needGo;
    }

    public GameObject SpawnObject(string path, Transform parent)
    {
        GameObject needGo = SpawnObject(path);
        needGo.transform.SetParent(parent);
        needGo.transform.localPosition = Vector3.zero;
        return needGo;
    }

    public GameObject SpawnObject(string path, Vector3 pos, Quaternion qua)
    {
        GameObject needGo;
        if (_pool.ContainsKey(path) && _pool[path].Count > 0)
        {
            needGo = _pool[path][0];
            _pool[path].RemoveAt(0);
        }
        else
        {
            needGo = AssetsManager.PrefabManager.GetInstance().CreateGameObjectByPrefab(path, pos, qua);
            //去掉(clone)
            needGo.name = path;
        }

        needGo.SetActive(true);
        return needGo;
    }

    public void RecycleGo(GameObject go)
    {
        go.SetActive(false);

        if (_pool.ContainsKey(go.name))
        {
            _pool[go.name].Add(go);
        }
        else
        {
            _pool.Add(go.name, new List<GameObject>() {go});
        }
    }

    public void RecycleGo(List<GameObject> gameObjects)
    {
        for (int i = 0; i < gameObjects.Count; i++)
        {
            gameObjects[i].SetActive(false);
            if (_pool.ContainsKey(gameObjects[i].name))
            {
                _pool[gameObjects[i].name].Add(gameObjects[i]);
            }
            else
            {
                _pool.Add(gameObjects[i].name, new List<GameObject>() {gameObjects[i]});
            }
        }

        gameObjects.Clear();
    }
}